// Begin Date manipulation functions
//<Script language=javascript>
// Use user Date preference to determine order of date elements
var userMonth
var userDay
var userYear
var dateDelim
var dateStrArray

function setDateArray() {
	switch (userDatePreference) {
		case  OT_DateFormat_MDY_slash:
		userMonth = dateStrArray[0];
		userDay = dateStrArray[1];
		userYear = dateStrArray[2];
		dateDelim = '/';
		break;
	case OT_DateFormat_MDY_hyphen:
		userMonth = dateStrArray[0];
		userDay = dateStrArray[1];
		userYear = dateStrArray[2];
		dateDelim = '-';
		break;
	case OT_DateFormat_MDY_dot:
		userMonth = dateStrArray[0];
		userDay = dateStrArray[1];
		userYear = dateStrArray[2];
		dateDelim = '.';
		break;
	case OT_DateFormat_DMY_slash:
		userDay = dateStrArray[0];
		userMonth = dateStrArray[1];
		userYear = dateStrArray[2];
		dateDelim = '/';
		break;
	case  OT_DateFormat_DMY_hyphen:
		userDay = dateStrArray[0];
		userMonth = dateStrArray[1];
		userYear = dateStrArray[2];
		dateDelim = '-';
		break;
	case  OT_DateFormat_DMY_dot:
		userDay = dateStrArray[0];
		userMonth = dateStrArray[1];
		userYear = dateStrArray[2];
		dateDelim = '.';
		break;
	case OT_DateFormat_YMD_slash:
		userYear = dateStrArray[0];
		userMonth = dateStrArray[1];
		userDay = dateStrArray[2];
		dateDelim = '/';
		break;
	case OT_DateFormat_YMD_hyphen:
		userYear = dateStrArray[0];
		userMonth = dateStrArray[1];
		userDay = dateStrArray[2];
		dateDelim = '-';
		break;
	case OT_DateFormat_YMD_dot:
		userYear = dateStrArray[0];
		userMonth = dateStrArray[1];
		userDay = dateStrArray[2];
		dateDelim = '.';
	}	
}

function jsTrim(str)
{
    var tmpStr
    tmpStr = str
    tmpStr = tmpStr.replace(/^\s*/, "");
    tmpStr = tmpStr.replace(/\s*$/, "");
    return tmpStr
}
 
// Begin validation functions

var errorMessage
 
// Has form already been submitted?
var submitcount=0;

function submitOnce()
{
	if (submitcount == 0)
	{
      	submitcount++;
      	return true;
    }
   	else
   	{
      	errorMessage = OTGetUserMessage("ValidationsJS", "AlreadySubmitted");
      	return false;
	}
}

// Is form field empty?

function isEmpty(form_object, fieldString) {
	var inputStr = form_object.value
	if (inputStr == null || inputStr == "")
	{
		errorMessage = OTFormatUserMessage("ValidationsJS","FieldValueEnter",fieldString)
		return true
	}
	else
	{
	return false
	}
}

// Determine the date string delimiters and their validity

function delimiterIsValid(dateStr)
{
	var err = 0
	//what's the separator?  "/" "." or "-" are valid, but only one separator can be found
		
	if (dateStr.lastIndexOf("/") >= 0)
	{
		if ((dateStr.lastIndexOf(".") == -1) && (dateStr.lastIndexOf("-") == -1)) {
			dateStrArray = dateStr.split("/");
		}
		else
		{
			err = 1;
		}
	}
	else if (dateStr.lastIndexOf("-") >= 0)
	{
		if ((dateStr.lastIndexOf(".") == -1) && (dateStr.lastIndexOf("/") == -1))
		{
			dateStrArray = dateStr.split("-");
		}
		else
		{
			err = 1;
		}
	}
	else if (dateStr.lastIndexOf(".") >= 0)
	{
		if ((dateStr.lastIndexOf("/") == -1) && (dateStr.lastIndexOf("-") == -1))
		{
			dateStrArray = dateStr.split(".");
		}
		else
		{
			err = 1;
		}
	}
	else
	{
		// no occurrence of a valid separator
		errorMessage = OTGetUserMessage("ValidationsJS", "InvalidDates");
		return false;
	}
		
	if (err == 1)  // multiple valid separators 
	{ 
		errorMessage = OTGetUserMessage("ValidationsJS", "InvalidDates");
		return false;
	}
return true
}

// Are all elements present?
function fullDateEntered(dateStrArray)
{
	// ok, dateStrArray must have 3 items...
	if (dateStrArray.length != 3)
	{
		errorMessage = OTGetUserMessage("ValidationsJS", "AllDatePartsSpecified");
		return false;
	}
return true
}

// Remove leading zeros in dates
function stripLeadZero(theNumber)
{
	var numString = theNumber.toString(10)
	numString = parseInt(numString,10)
	return numString
}

// Is the day of month in range?
function monthLengthValid(userMonth,userDay)
{
	userMonth = stripLeadZero(userMonth)
	userDay = stripLeadZero(userDay)
	var months = new Array("",OTGetUserMessage("DateTime","January"), 
								OTGetUserMessage("DateTime","February"),
								OTGetUserMessage("DateTime","March"),
								OTGetUserMessage("DateTime","April"),
								OTGetUserMessage("DateTime","May"),
								OTGetUserMessage("DateTime","June"),
								OTGetUserMessage("DateTime","July"),
								OTGetUserMessage("DateTime","August"),
								OTGetUserMessage("DateTime","September"),
								OTGetUserMessage("DateTime","October"),
								OTGetUserMessage("DateTime","November"),
								OTGetUserMessage("DateTime","December"));
	
	if (userMonth == 2)
	{
	    if (typeof(userYear) == 'undefined' || userYear == -1)
	    {
	        if (userDay <= 29) return true
	        else
	        {
	            errorMessage = OTFormatUserMessage("ValidationsJS","FebDaysMaxNoYear", OTGetUserMessage("DateTime", "February"))
	            return false	        
	        }
	    }
	    
		if (leapMonthValid(userDay,userYear))
		{
			return true
		}
		else
		{
			return false
		}
	}
	else
	{	
		if ((userMonth == 4 || userMonth == 6 || userMonth == 9 || userMonth == 11) && userDay > 30)
		{
			errorMessage = OTFormatUserMessage("ValidationsJS","MonthDaysMax", OTGetUserMessage("DateTime", months[userMonth]), "30");
			return false
		} 
		else if (userDay > 31)
		{
			errorMessage = OTFormatUserMessage("ValidationsJS","MonthDaysMax", OTGetUserMessage("DateTime", months[userMonth]), "31");
			return false
		}
	}
return true
}

// check the entered February date for too high a value 
function leapMonthValid(userDay,userYear)
{
	if (userYear % 4 > 0 && userDay > 28)
	{
		errorMessage = OTFormatUserMessage("ValidationsJS","FebDaysMax", OTGetUserMessage("DateTime", "February"), userYear, "28");
		return false
	}
	else if (userDay > 29)
	{
		errorMessage = OTFormatUserMessage("ValidationsJS","FebDaysMax", OTGetUserMessage("DateTime", "February"), userYear, "29")
		return false
	}
return true
}

// Is Month in range?
function monthIsValid(userMonth)
{


	if (!isNaN(userMonth))
	{
		if (userMonth < 1 || userMonth > 12)
		{
			errorMessage = OTFormatUserMessage("ValidationsJS","MonthDayRange", OTGetUserMessage("DateTime", "January"), OTGetUserMessage("DateTime", "December")) + "\n";
			errorMessage += OTFormatUserMessage("ValidationsJS","CheckDateExample") + "\n";
			errorMessage += OTGetUserMessage("ValidationsJS", "ProfileChangeFormat");
			return false
		}
	
	}else
	{
		errorMessage = OTGetUserMessage("ValidationsJS", "DatesOnlyNumbers");
		return false
	}
return true
}

// Day of month check - with leap year calculation
function dayIsValid(userDay)
{
	if (!isNaN(userDay))
	{
		if (userDay != 0 && userDay != "")
		{
			if (monthLengthValid(userMonth,userDay))
			{
				if(leapMonthValid(userMonth,userDay,userYear))
				{
					return true
				}
				else
				{
					return false
				}
			}
			return false
		}
		else
		{
			errorMessage = OTGetUserMessage("ValidationsJS", "EnterValidDay");
			return false 
		}
	}
	else
	{
		errorMessage = OTGetUserMessage("ValidationsJS", "DatesOnlyNumbers");
		return false
	}
return true
}

// Is year in range? Also returns 4 digit year w/y2k conversion
var longYear
function yearIsValid(userYear, fieldString)
{
	if (!isNaN(userYear))
	{
		if (userYear != "")
		{
			userYear = stripLeadZero(userYear)
			if (((userYear > 99) && (userYear < 999)) || (userYear > 9999))
			{
				errorMessage = OTGetUserMessage("ValidationsJS", "InvalidDates");
				return false;
			}
			else
			{
				if(userYear < 30)
				{
					longYear = userYear + 2000;
					return true;
				}
				else if (userYear >= 30 && userYear < 100)
				{
						longYear = userYear + 1900;
						return true;
				}
				else if (userYear < 1900 || userYear > 2078)
				{
					errorMessage = OTFormatUserMessage("ValidationsJS", "DateYearRange", fieldString);
					return false;
				}
				else
				{
					longYear = userYear
					return true
				}
			}
		}
		else
		{
			errorMessage = OTGetUserMessage("ValidationsJS", "EnterValidYear");
			return false 
		}
	}
	else
	{
		errorMessage = OTGetUserMessage("ValidationsJS", "DatesOnlyNumbers");
		return false
	}
return true
}

// ------------------------------//		
// Main date validation function //
//-------------------------------//

function checkDate(frmDateObject, fieldString)
{
	if(typeof(frmDateObject.value) == "undefined") return;
	
	dateStr = jsTrim(frmDateObject.value);
	var err=0
		
	if (!isEmpty(frmDateObject, fieldString))
	{
		if (delimiterIsValid(dateStr))
		{
			if(fullDateEntered(dateStrArray))
			{
				setDateArray()
				if (monthIsValid(userMonth))
				{
					if (dayIsValid(userDay))
					{
						if (yearIsValid(userYear,fieldString))
						{
							return true
						}
						else
						{
							return false
						}
					return false
					}
				return false
				}
			return false
			}
		return false
		}
	return false
	}
}

//	Utility function takes a string and returns true
//	if it contains only whitespace chars
 
function isBlank(str)
{
	var s = String(str);
	if(s == '') return true;
	if(s == null) return true;
	for (var i = 0; i < s.length; i++)
	{
		var c = s.charAt(i);
		if ((c != " ") && (c != '\n') && (c != '\t')) return false;
	}
	return true;
}

// Generic form validation function
// Takes a form object reference and returns true if all tests pass
// Calling function must define a parameter of fields to be tested with
// "required"

function validateForm(f)
{
	for (var i = 0; i < f .length; i++)
	{
		var e = f.elements[i];
		if (((e.type == "text") || (e.type == "textarea")) && e.required)
		{
			if((e.value == null) || (e.value == "") || (isBlank(e.value)))
			{	
				alert(OTGetUserMessage("ValidationsJS", "AllRequiredFields"));
				return false;
			}
			else
			{
				return true;
			}
		}
	}
}

function isNumeric(field)
{
	return isNumericValue(field.value);
}

function isNumericValue(val)
{
	var valid = "0123456789"
	var ok = "yes";
	var temp;
	for (var i=0; i < val.length; i++) 
	{
		temp = "" + val.substring(i, i+1);
		if (valid.indexOf(temp) == "-1") ok = "no";
	}
	if (ok == "no") 
	{
		return false;
	}
	return true
}

function isPosNumber(value)
{
    if (isNaN(value)) return false
    else if (value < 1) return false
    else if (parseInt(value) != value) return false
    
    return true;
}

function isPosNumberOrZero(value)
{
    if (isNaN(value)) return false
    else if (value < 0) return false
    else if (parseInt(value) != value) return false
    
    return true;
}

function validNumber(num, lower, upper, decOK) {
// num - value being tested
// lower - lower numeric limit
// upper - upper numeric limit
// decOK - must it be an integer, or are float numbers OK
// returns true if the number is blank

//can use OTFormatUserMessage("ValidationsJS", "FieldIntegerMinMax", min, max);
//for your alert.

	if(!isBlank(num) && (isNaN(num) || parseFloat(num) < parseFloat(lower)
						|| parseFloat(num)>parseFloat(upper)
						|| (!decOK && parseInt(num,10)!=parseFloat(num)))) return false;
	return true;
}

function validFormattedMoney(money, format, currency)
{
	//This requires GetNumberSeparators function which is in functions.js
	//I couldn't just check JS_UnformatMoney for false because 0 was is valid 		
	if (typeof(currency) == 'undefined')
	{
		currency = '$'
	}
	var strRegex
	if (currency.length == 3) {
		strRegex = new RegExp(currency, "g")
	} else {
		strRegex = new RegExp("\\" + currency, "g")
	}
	var tmpNum = money.replace(strRegex, '')
		
	GetNumberSeparators(format)
		
	// Strip thousands separators
	strRegex.compile("\\" + thouSep, "g")
	tmpNum = tmpNum.replace(strRegex, '')
	
	strRegex.compile("\\" + decSep, "g")
	tmpNum = tmpNum.replace(strRegex, '.')
				
	if (isNaN(tmpNum))
	{ 
		return false;
	}
		
	return true;

}

function validEmailList(emailTxt) {

	/*
	Firebug tests should all return true.
	console.log(true  == validEmailList("a@b.com,b@b.com,c@c.com;d@.com   ;;e@e.com , f@f.com ;g@g.com;h@h.com"));
	console.log(true  == validEmailList("a@b.com,b@b.com,c@c.com;d@.com   ;;e@e.com , f@f.com ;g@g.com;h@h.com;"));
	console.log(true  == validEmailList("a@a.com"));
	console.log(true  == validEmailList("a@a.com;;; b@a.com;;;"));
	console.log(true  == validEmailList("a@a.com,b@b.com,"));
	console.log(false == validEmailList("a@"));
	console.log(false == validEmailList("a@a.com,bbb"));
	console.log(false == validEmailList("bbb,a@a.com"));
	console.log(false == validEmailList(""));
	console.log(false == validEmailList("   "));
	console.log(false  == validEmailList("a@a. com , b@ b.com"));
	true //leave this line when you paste into Firebug to avoid an undefined
*/	


	if (!emailTxt) {
		return false;
	}
	
	//trim main string to remove whitespace from first and list items in the list
	//replace comma with semi-colon, so both delimiters work
	//replace duplicate semi-colons (like ;;)
	//remove white space around the seperators 
	var tmpEmailTxt = jsTrim(emailTxt);
	tmpEmailTxt = tmpEmailTxt.replace(/,/ig, ';').replace(/;+/ig, ';');
	tmpEmailTxt = tmpEmailTxt.replace(/\s*;\s*/ig, ';');	
	emailArr = tmpEmailTxt.split(';');
	
	
	//if last item is empty because the string ended in; then, remove it.
	if (emailArr.length && !emailArr[emailArr.length - 1])
	{
		emailArr.pop(); // remove last item
	}
	
	if (emailArr.length == 0) return false; //nothing in the list
	
	var lastIndex = (emailArr.length - 1);
	for (var i = 0; i <= lastIndex; i++) 
	{
		if (!validEmail(emailArr[i])) 
		{
			return false;
		}
		
		// valid email does not test for spaces inside of the email, so look for that here
		if (emailArr[i].indexOf(' ',0) != -1)
		{
				return false;
		}
		
	}
	
	return true;
}

function validEmail(emailTxt)
{
	if (!emailTxt)
		return false;		

	if (emailTxt.indexOf ('@',0) == -1 || 
		emailTxt.indexOf ('.',0) == -1 || 
		emailTxt.length < 6 ||
		emailTxt.indexOf('@', 0) != emailTxt.lastIndexOf('@') ||
		emailTxt.indexOf(',', 0) != -1)
		return false;
	
	return true;
}

function validate_page(arrFields)
{

/*
	  This is an all purpose checking utility.
	  To use it, create an array on your main page
	  They key of the array is the field name (document.frmMain is assumed)
	  
	  Valid checks include (isBlank, date, email, etc.)

		var arrFields = {};
		arrFields['CompanyName'] = Array('Company Name', 'isBlank')
		arrFields['StartDate'] = Array('Start Date', 'date')
		
		in your page submit, you would do something like: 
		
		if (!validate_page(arrFields)) {
			return false;
		}
*/

	for(var key in arrFields) //ac ok -- array is safe, because while we are doing a for loop, we are only looking for specific properties
	{
		var field = document.frmMain[key];
		if (!field) {//if not on frmMain, try somewhere else
			field = $(key);
		}
		switch (arrFields[key][1])
		{
			case "isBlank":
				if (isBlank(field.value))
				{
					alert(OTFormatUserMessage("ValidationsJS", "FieldValueEnter", arrFields[key][0]));
					tryFocus(field);
					return false;
				}
				break;
			case "email":
				if (!validEmail(field.value))
				{
					alert(OTFormatUserMessage("ValidationsJS", "FieldValueInvalid", arrFields[key][0]));
					field.select();
					tryFocus(field);
					return false;
				}
				break;
			case "emailList":
			
				// auto-correct email list:
				//    removes spaces, converts commas to semi-colons and condense multiple semi-colons to one
				if (field && field.value) {
					field.value = field.value.replace(/ /ig, '').replace(/,/ig, ';').replace(/;+/ig, ';');
				}
				
				// now validate it			
				if (!validEmailList(field.value)) 
				{
					alert(OTFormatUserMessage("ValidationsJS", "FieldValueListInvalid", arrFields[key][0]));
					field.select();
					tryFocus(field);
					return false;
				}
				
				break;
			case "date":
				if (!checkDate(field, arrFields[key][0]))
				{
					alert(errorMessage) //global variable created during checkDate
					field.select();
					tryFocus(field);
					return false;
				}
				break;
			case "isPosNumber":
				if (!isPosNumber(field.value))
				{
					alert(OTFormatUserMessage("ValidationsJS", "FieldNumberOnly", arrFields[key][0]));
					//alert('Please enter a number for the ' + arrFields[key][0]);
					field.select();
					tryFocus(field);
					return false;
				}
				break;
			case "isPosNumberOrZero":
				if (!isPosNumberOrZero(field.value))
				{
					alert(OTFormatUserMessage("ValidationsJS", "FieldNumberOnly", arrFields[key][0]));
					//alert('Please enter a number for the ' + arrFields[key][0]);
					field.select();
					tryFocus(field);
					return false;
				}
				break;
			case "isNumeric":
				if (!isNumeric(field))
				{
					alert(OTFormatUserMessage("ValidationsJS", "FieldNumberOnly", arrFields[key][0]));
					field.select();
					tryFocus(field);
					return false;
				}
				break;
		}
	}
	return true;
}

function tryFocus(field)
{
	try {field.focus()}
	catch (e) {}
}